from django.core.management.base import BaseCommand, CommandError
from store.models import Order
import datetime
from optparse import make_option

class Command(BaseCommand):
    help = 'Closes the specified order for unpaid'
    option_list = BaseCommand.option_list + (
        make_option('--list',
            action='store_true',
            dest='list',
            default=False,
            help='list all un-paied orders'),
        make_option('--run',
            action='store_true',
            dest='run',
            default=False,
            help='close all expired and un-paied orders')   
        )

    def handle(self, *args, **options):
        t = datetime.datetime.now() - datetime.timedelta(days=1)
        d = t.strftime("%Y-%m-%d")
        if options['list']:
            orders = Order.objects.filter(status=Order.New).filter(created_at__lte=d) #.update(status=Order.Closed)
            print "Total: ", orders.count()
            i = 0
            for order in orders[0:10]:
                print "#", i, ": ", order, " ", order.created_at;
                i+=1
                if i > 5:
                    print "..."
                    break
        elif options['run']:
            affected_rows = Order.objects.filter(status=Order.New).filter(created_at__lte=d).update(status=Order.Closed)
            print "Total: ", affected_rows
        else:
            print self.help
